package com.jinyi.wwdeng.autodialer.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.edit
import com.jinyi.wwdeng.autodialer.manager.CallTaskManager
import com.jinyi.wwdeng.autodialer.manager.ReportTaskManager
import com.jinyi.wwdeng.autodialer.manager.UploadTaskManager
import com.jinyi.wwdeng.autodialer.repository.CallTaskRepository
import com.jinyi.wwdeng.autodialer.utils.CallStateHelper
import com.jinyi.wwdeng.autodialer.utils.ServiceConfig
import com.jinyi.wwdeng.autodialer.utils.event.EventAction
import com.jinyi.wwdeng.autodialer.utils.event.EventAction.ACTION_UPDATE_SERVICE
import com.jinyi.wwdeng.autodialer.utils.event.EventAction.EXTRA_STATUS
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable.isActive
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Duration.Companion.seconds

class AutoCallService: Service() {
    // 配置
    private val config = ServiceConfig()

    //数据库操作类
    private val taskRepository: CallTaskRepository by lazy { CallTaskRepository.getInstance(this) }

    // Manager实例
    private lateinit var callTaskManager: CallTaskManager
    private lateinit var uploadTaskManager: UploadTaskManager
    private lateinit var reportTaskManager: ReportTaskManager

    //通话状态监听帮助类
    private lateinit var callStateHelper: CallStateHelper

    // 协程作用域
    private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    // 定时任务引用
    private var dialJob: Job? = null
    private var uploadJob: Job? = null
    private var reportJob: Job? = null

    // 恢复点持久化
    private val sharedPrefs by lazy {
        getSharedPreferences("AutoCallService", Context.MODE_PRIVATE)
    }

    // 服务状态管理
    enum class ServiceState {
        STOPPED, STARTING, RUNNING, STOPPING
    }
    private var serviceState = ServiceState.STOPPED
    private val stateLock = Any()

    companion object {
        const val ACTION_START = "ACTION_START"
        const val ACTION_STOP = "ACTION_STOP"
        const val NOTIFICATION_ID = 1001
        const val CHANNEL_ID = "auto_call_channel"

        // 单例模式，用于Activity检查服务状态
        private var instance: AutoCallService? = null
        fun isServiceRunning(): Boolean {
            return instance?.getServiceState() == ServiceState.RUNNING
        }
    }

    override fun onCreate() {
        super.onCreate()
        Log.d("AutoCallService", "onCreate Service >>>>>>>>>>>>>>>")
        instance = this

        // 初始化Manager
        callTaskManager = CallTaskManager(this, taskRepository, config)
        uploadTaskManager = UploadTaskManager(this,taskRepository, config)
        reportTaskManager = ReportTaskManager(this,taskRepository, config)

        // 创建通知渠道
        createNotificationChannel()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("AutoCallService", "onStartCommand >>>>>>>>>${intent?.action}")
        when (intent?.action) {
            ACTION_START -> {
                handleStartAction()
                START_STICKY
            }
            ACTION_STOP -> {
                handleStopAction()
                START_NOT_STICKY
            }
            else -> {
                // 服务被系统重启，尝试恢复
                handleSystemRestart()
                START_STICKY
            }
        }
        return START_NOT_STICKY
    }

    private fun handleStartAction() {
        synchronized(stateLock) {
            when (serviceState) {
                ServiceState.RUNNING -> {
                    Log.w("AutoCallService", "服务已在运行中，忽略重复启动请求")
                    return
                }
                ServiceState.STARTING -> {
                    Log.w("AutoCallService", "服务正在启动中，忽略重复启动请求")
                    return
                }
                ServiceState.STOPPING -> {
                    Log.w("AutoCallService", "服务正在停止中，等待停止完成后重新启动")
                    // 可以在这里添加等待逻辑，或者直接返回
                    return
                }
                ServiceState.STOPPED -> {
                    // 正常启动流程
                    serviceState = ServiceState.STARTING
                }
            }
        }
        //通知服务已启动
        EventAction.sendBroadcast(
            ACTION_UPDATE_SERVICE,
            EXTRA_STATUS to "start"
        )

        Log.d("AutoCallService", "启动自动呼叫服务")
        try {
            startForegroundService()
            startAllTasks()
            saveRecoveryPoint("SERVICE_STARTED")

            synchronized(stateLock) {
                serviceState = ServiceState.RUNNING
            }
            Log.d("AutoCallService", "服务启动完成")

        } catch (e: Exception) {
            Log.e("AutoCallService", "服务启动失败", e)
            synchronized(stateLock) {
                serviceState = ServiceState.STOPPED
            }
        }
    }

    private fun handleStopAction() {
        synchronized(stateLock) {
            if (serviceState == ServiceState.STOPPED) {
                Log.w("AutoCallService", "服务已停止，忽略停止请求")
                return
            }
            serviceState = ServiceState.STOPPING
        }

        //通知服务已启动
        EventAction.sendBroadcast(
            ACTION_UPDATE_SERVICE,
            EXTRA_STATUS to "stop"
        )
        Log.d("AutoCallService", "停止自动呼叫服务")
        serviceScope.launch {
            try {
                stopAllTasks()
                clearRecoveryPoint()

                withContext(Dispatchers.Main) {
                    synchronized(stateLock) {
                        serviceState = ServiceState.STOPPED
                    }
                    stopSelf()
                    Log.d("AutoCallService", "服务停止完成")
                }
            } catch (e: Exception){
                Log.e("AutoCallService", "服务停止异常", e)
            }
        }
    }

    private fun handleSystemRestart() {
        Log.w("AutoCallService", "服务被系统重启，尝试恢复")
        synchronized(stateLock) {
            serviceState = ServiceState.STARTING
        }

        try {
            // 服务被系统重启，尝试恢复
            tryRecoverFromCrash()

            synchronized(stateLock) {
                serviceState = ServiceState.RUNNING
            }
            Log.d("AutoCallService", "系统重启恢复完成")
            //通知服务已启动
            EventAction.sendBroadcast(
                ACTION_UPDATE_SERVICE,
                EXTRA_STATUS to "start"
            )
        } catch (e: Exception) {
            Log.e("AutoCallService", "系统重启恢复失败", e)
            synchronized(stateLock) {
                serviceState = ServiceState.STOPPED
            }
        }
    }

    // 获取服务状态（供外部调用）
    fun getServiceState(): ServiceState {
        return synchronized(stateLock) {
            serviceState
        }
    }

    private fun startForegroundService() {
        val notification = createNotification()
        startForeground(NOTIFICATION_ID, notification)
        Log.d("AutoCallService", "前台服务已启动")
    }

    private fun createNotificationChannel() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val channel = NotificationChannel(CHANNEL_ID, "自动呼叫服务", NotificationManager.IMPORTANCE_LOW).apply {
                description = "自动拨号、录音、上传服务运行中"
            }

            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }

    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("自动呼叫服务")
            .setContentText("服务运行中...")
            .setSmallIcon(android.R.drawable.ic_btn_speak_now)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()
    }

    /**
     * 启动所有任务
     */
    private fun startAllTasks() {
        initCallState()
        startDialScheduler()
        startUploadScheduler()
        startReportScheduler()
    }

    /**
     * 停止所有任务
     */
    private fun stopAllTasks() {
        callTaskManager.shutdown()

        // 取消所有协程任务
        dialJob?.cancel()
        uploadJob?.cancel()
        reportJob?.cancel()

        callStateHelper.release()
        Log.d("AutoCallService", "所有任务已停止")
    }

    // ==================== 定时任务1 - 拨号调度器 ====================
    private fun startDialScheduler() {
        dialJob = serviceScope.launch {
            while (isActive) {
                try {
                    Log.d("DialScheduler", "执行拨号调度")
                    //当前状态没有在通话中
                    if (!callStateHelper.isInCall()){
                        callTaskManager.handleDialScheduling()
                    }
                    delay(config.dialInterval.seconds)
                } catch (e: CancellationException) {
                    Log.d("DialScheduler", "拨号调度器被取消")
                    break
                } catch (e: Exception) {
                    Log.e("DialScheduler", "拨号调度器异常", e)
                    delay(5.seconds)
                }
            }
        }
    }

    // ==================== 定时任务2 - 文件上传器 ====================
    private fun startUploadScheduler() {
        uploadJob = serviceScope.launch {
            while (isActive) {
                try {
                    Log.d("UploadScheduler", "执行上传调度")
                    uploadTaskManager.handleUploadScheduling()
                    delay(config.uploadInterval.seconds)
                } catch (e: CancellationException) {
                    Log.d("UploadScheduler", "上传调度器被取消")
                    break
                } catch (e: Exception) {
                    Log.e("UploadScheduler", "上传调度器异常", e)
                    delay(5.seconds)
                }
            }
        }
    }

    // ==================== 定时任务3 - 数据上报器 ====================
    private fun startReportScheduler() {
        reportJob = serviceScope.launch {
            while (isActive) {
                try {
                    Log.d("ReportScheduler", "执行上报调度")
                    reportTaskManager.handleReportScheduling()
                    delay(config.reportInterval.seconds)
                } catch (e: CancellationException) {
                    Log.d("ReportScheduler", "上报调度器被取消")
                    break
                } catch (e: Exception) {
                    Log.e("ReportScheduler", "上报调度器异常", e)
                    delay(5.seconds)
                }
            }
        }
    }

    // ==================== 持久化恢复点 ====================
    private fun saveRecoveryPoint(point: String) {
        sharedPrefs.edit().apply {
            putString("recovery_point", point)
            putLong("recovery_time", System.currentTimeMillis())
            apply()
        }
        Log.d("AutoCallService", "保存恢复点: $point")
    }

    private fun clearRecoveryPoint() {
        sharedPrefs.edit { remove("recovery_point") }
        Log.d("AutoCallService", "清除恢复点")
    }

    private fun tryRecoverFromCrash() {
        val recoveryPoint = sharedPrefs.getString("recovery_point", null)
        if (recoveryPoint != null && serviceState != ServiceState.STOPPING) {
            Log.w("AutoCallService", "检测到服务异常重启，恢复点: $recoveryPoint")
            startForegroundService()
            startAllTasks()
            // 可以在这里根据恢复点执行特定的恢复逻辑
        } else {
            Log.d("AutoCallService", "没有恢复点，不做恢复")
        }
    }

    /**
     * 初始化通话状态监听
     */
    private fun initCallState(){
        // 初始化通话状态监听器
        callStateHelper = CallStateHelper(this)
        // 设置监听回调
        val callStateListener = object : CallStateHelper.CallStateListener {
            override fun onCallStateIdle() {
                // 空闲状态
                Log.e("TAG",">>>>>>>>>>>>>通话状态: 空闲中")
                callTaskManager.onCallEnded()
            }
            override fun onCallStateRinging() {
                // 响铃状态
                Log.e("TAG",">>>>>>>>>>>>>通话状态: 来电响铃中")
            }
            override fun onCallStateOffHook() {
                // 通话中
                Log.e("TAG", "电话接通，开始录音")
                callTaskManager.onCallAnswered()
            }
        }
        callStateHelper.startListening(callStateListener)
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onDestroy() {
        super.onDestroy()
        Log.d("AutoCallService", "服务销毁")
        synchronized(stateLock) {
            serviceState = ServiceState.STOPPED
        }
        instance = null
        serviceScope.cancel() // 取消整个协程作用域
        stopAllTasks()
    }
}